package com.lt.integration.jpa.validation;

import cn.hutool.core.bean.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证字段不能同时为空
 * @author: xiaobin
 * @create: 2020-05-12 15:23
 */
public class NotAllNullValidator implements ConstraintValidator<NotAllNull, Object> {
    private static final Logger log = LoggerFactory.getLogger(NotAllNullValidator.class);

    private String message;
    private String[] values;

    @Override
    public void initialize(NotAllNull notAllNull) {
        message = notAllNull.message();
        values = notAllNull.values();
    }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context) {
        for (String propName : values) {
            Object value = BeanUtil.getFieldValue(obj, propName);
            log.debug("value: {}", value);
            // 只要有一个不为空 直接返回成功
            if (value != null) {
                return true;
            }
        }
        for (String propName : values) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addPropertyNode(propName).addConstraintViolation();
        }
        return false;
    }
}
